package com.dtp.core.notify.base;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.dtp.common.constant.DingNotifyConst;
import com.dtp.common.entity.MarkdownReq;
import com.dtp.common.entity.NotifyPlatform;
import com.dtp.common.em.NotifyPlatformEnum;
import com.dtp.common.util.DingSignUtil;
import com.dtp.common.util.TimeUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;

import static com.dtp.common.constant.DingNotifyConst.DING_NOTICE_TITLE;

/**
 * 钉钉通知者类 https://oapi.dingtalk.com/robot/send?access_token=
 *
 * @author yanhom
 * @since 1.0.0
 *
 * @remark muse
 **/
@Slf4j
public class DingNotifier implements Notifier {

    @Override
    public String platform() {return NotifyPlatformEnum.DING.name().toLowerCase();} // "ding"

    /** 执行钉钉通知发送操作 */
    @Override
    public void send(NotifyPlatform platform, String text) {
        MarkdownReq.Markdown markdown = new MarkdownReq.Markdown();
        markdown.setTitle(DING_NOTICE_TITLE); // DING_NOTICE_TITLE="动态线程池通知"
        markdown.setText(text);

        MarkdownReq.At at = new MarkdownReq.At();
        List<String> mobiles = Lists.newArrayList(StringUtils.split(platform.getReceivers(), ','));
        at.setAtMobiles(mobiles);                                   // 设置接受者列表
        if (CollectionUtils.isEmpty(mobiles)) at.setAtAll(true);    // 如果没有配置接受者，则发送搜有人

        MarkdownReq markdownReq = new MarkdownReq();
        markdownReq.setMsgtype("markdown");
        markdownReq.setMarkdown(markdown);
        markdownReq.setAt(at);

        // 获得钉钉发送通知的url
        String hookUrl = getTargetUrl(platform.getSecret(), platform.getUrlKey());
        try {
            HttpResponse response = HttpRequest.post(hookUrl).body(JSONUtil.toJsonStr(markdownReq)).execute();
            if (Objects.nonNull(response))
                log.info("DynamicTp notify, ding send success, response: {}, request: {}", response.body(), JSONUtil.toJsonStr(markdownReq));
        } catch (Exception e) {
            log.error("DynamicTp notify, ding send failed...", e);
        }
    }

    /** 构建钉钉发送目标url */
    private String getTargetUrl(String secret, String accessToken) {
        // 如果不需要秘钥，则直接发送
        if (StringUtils.isBlank(secret)) return DingNotifyConst.DING_WEBHOOK + accessToken;

        // 如果需要秘钥，则指定秘钥签名，然后再发送
        long timestamp = TimeUtil.currentTimeMillis();
        String sign = DingSignUtil.dingSign(secret, timestamp);
        return DingNotifyConst.DING_WEBHOOK + accessToken + "&timestamp=" + timestamp + "&sign=" + sign;
    }
}
